<template>
  <el-dialog v-model="dialogVisible" :title="`${rowId?'编辑':'新增'}货物`" width="80%" :before-close="handleClose">
    <el-table :data="tableParams.rows" @select="handleSelectionChange" v-if="!rowId">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="50" />
      <el-table-column prop="lotNo" label="批次号" align="center" min-width="100" />
      <el-table-column prop="cargoSn" label="货物编码" />
      <el-table-column prop="cargoName" label="货物名称" />
      <el-table-column prop="plannedNum" label="计划出库数量" />
      <!-- <el-table-column prop="num" label="实际出库数量" /> -->
      <el-table-column label="单位">
        <template #default="scope">
          <selectUnit v-model="scope.row.cargoUnit" readonly="1"></selectUnit>
        </template>
      </el-table-column>
      <el-table-column prop="supplierName" label="供应商" />
      <el-table-column prop="cargoWeight" label="重量（KG）" />
      <el-table-column prop="cargoVolume" label="体积(m³)" />
      <el-table-column prop="cargoSpec" label="规格" />
      <el-table-column prop="remark" label="备注" align="center" />
    </el-table>

    <Pagination v-if="tableParams['total'] && !rowId" :total="tableParams['total']" v-model:page="form.pageNum" v-model:limit="form.pageSize" @pagination="getInfo" />

    <el-table :data="selectArr" style="width: 100%" v-if="selectArr.length">
      <el-table-column prop="lotNo" label="批次号" align="center" width="150" />
      <el-table-column prop="cargoSn" label="货物编码" align="center" width="150" />
      <el-table-column prop="cargoName" label="货物名称" />
      <el-table-column label="托盘码" align="center" width="200">
        <template #default="scope">
          <selectTray v-model="scope.row.trayId" disabled></selectTray>
        </template>
      </el-table-column>
      <el-table-column label="出库数量" align="center" width="150">
        <template #default="scope">
          <el-input v-model="scope.row.num" placeholder="数量" />
        </template>
      </el-table-column>
      <el-table-column prop="totalNum" label="剩余库存" />
      <el-table-column label="单价" align="center" width="150">
        <template #default="scope">
          <el-input v-model="scope.row.unitPrice" placeholder="单价" min-width="150" align="center" disabled />
        </template>
      </el-table-column>
      <el-table-column label="金额">
        <template #default="scope">
          {{(scope.row.num*scope.row.unitPrice)||0}}
        </template>
      </el-table-column>
      <el-table-column label="单位">
        <template #default="scope">
          <selectUnit v-model="scope.row.cargoUnit" readonly="1" disabled></selectUnit>
        </template>
      </el-table-column>
      <el-table-column label="货物属性" width="150" align="center">
        <template #default="scope">
          <el-select v-model="scope.row.type" placeholder="请选择">
            <el-option label="良品" :value="1" />
            <el-option label="不良品" :value="2" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="工厂">
        <template #default="scope">
          <selectFactory v-model="scope.row.factoryId" disabled></selectFactory>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="仓库">
        <template #default="scope">
          <selectStores v-model="scope.row.storeId" disabled></selectStores>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="库区">
        <template #default="scope">
          <selectStoreRegion v-model="scope.row.storeRegionId" disabled></selectStoreRegion>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="库位">
        <template #default="scope">
          <selectStoreLocation v-model="scope.row.storeRegionLocationId" disabled></selectStoreLocation>
        </template>
      </el-table-column>
      <el-table-column prop="cargoSpec" label="规格" width="100" align="center" />
      <el-table-column label="有效期" min-width="200" align="center">
        <template #default="scope">
          <DatePicker v-model="scope.row.validityDate"></DatePicker>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="save">
          确 认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed } from "vue";
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const { proxy } = getCurrentInstance();
let tableParams = ref({});
let dialogVisible = ref(false);
let cargos = ref([]);
let rowId = ref("");
const emit = defineEmits(["fatherMethods"]);
let handleClose = () => {
  form.value = {
    deliveryNo: "",
    lotNo: "",
    cargoSn: "",
    cargoName: "",
    supplierSn: "",
    supplierName: "",
    pageSize: 10,
    pageNum: 1,
  };
  selectArr.value = [];
  emit("fatherMethods");
  dialogVisible.value = false;
};
let deliveryNoCode = null;

let open = async (deliveryNo, planNo, row?) => {
  //如果是编辑
  if (row && row.id) {
    rowId.value = row.id;
    selectArr.value = [row];
  }
  deliveryNoCode = deliveryNo;
  form.value.deliveryNo = planNo;
  await getInfo();
  dialogVisible.value = true;
};
let form = ref({
  deliveryNo: "",
  lotNo: "",
  cargoSn: "",
  cargoName: "",
  supplierSn: "",
  supplierName: "",
  pageSize: 10,
  pageNum: 1,
});
let selectArr = ref([]);
let handleArr = [];
let getInfo = async () => {
  tableParams.value = await proxy.$apis.deliveryPlanDetailList(form.value);
  cargos.value = await counter.getCargoAmount(); //货物库存
  console.log("库存", cargos.value);
};
let handleSelectionChange = (selection, row) => {
  let list = proxy.$utils.deepcopy(selectArr.value);
  if (proxy.$utils.isFieldEqual(selection, "id", row.id)) {
    list.push({ ...row });
  } else {
    let index = proxy.$utils.findIndexByField(list, "id", row.id);
    list.splice(index, 1);
  }
  if (list.length) {
    selectArr.value = filterArray(list);
    console.log("selectArr.value", selectArr.value);
  }
};
let filterArray = (array) => {
  let cargos2 = [...cargos.value];
  array.forEach((element) => {
    let index = proxy.$utils.findIndexByField(
      cargos2,
      "batchNumber",
      element.lotNo
    );
    if (index >= 0) {
      let obj = {
        trayId: "",
        factoryId: "",
        unitPrice: "",
        cargoUnit: "",
        storeId: "",
        storeRegionId: "",
        storeRegionLocationId: "",
        cargoSpec: "",
      };
      for (let key in obj) {
        element[key] = cargos2[index][key];
      }
      element.totalNum = cargos2[index].num;
    }
  });
  return array;
};
let save = async () => {
  if (!selectArr.value.length)
    return proxy.$utils.showToast("请先选择要添加的货物", 0);
  let params = {
    amount: null,
    deliveryNo: "",
    lotNo: "",
    cargoId: "",
    cargoSn: "",
    cargoName: "",
    cargoWeight: "",
    cargoVolume: "",
    cargoUnit: "",
    cargoSpec: "",
    cargoSize: "",
    type: "",
    num: 1,
    unitPrice: null,
    trayId: "",
    supplierSn: "",
    factoryId: "",
    storeId: "",
    storeRegionId: "",
    storeRegionLocationId: "",
    validityDate: "",
  };
  for (let index = 0; index < selectArr.value.length; index++) {
    const element = selectArr.value[index];
    if (!element.num) return proxy.$utils.showToast(`${str}的数量不可为空`, 0);
    if (element.num > element.totalNum)
      return proxy.$utils.showToast(
        `${element.cargoName}出库数量不可大于库存${element.totalNum}`,
        0
      );
    if (!element.type)
      return proxy.$utils.showToast(
        `${element.cargoName}的货物属性不可为空`,
        0
      );
    element.amount = element.num * element.unitPrice;
    let obj = proxy.$utils.formatFunction(element, params);
    obj.deliveryNo = deliveryNoCode;
    if (rowId.value) obj.id = rowId.value;
    if (obj.id) {
      await proxy.$apis.deliveryRecordDetailPut(obj);
    } else {
      await proxy.$apis.deliveryRecordDetailAdd(obj);
    }
  }
  proxy.$utils.showToast("操作成功");
  handleClose();
};
let traySelect = (cargoId, trayId, subscript: number) => {
  let index = proxy.$utils.findIndexByField(handleArr, "cargoId", cargoId);
  let current = proxy.$utils.findIndexByField(
    handleArr[index].children,
    "trayId",
    trayId
  );
  let query = { ...handleArr[index].children[current] };
  let obj = {
    factoryId: query.factoryId,
    storeId: query.storeId,
    storeRegionId: query.storeRegionId,
    storeRegionLocationId: query.storeRegionLocationId,
    unitPrice: query.unitPrice,
    num: 1,
  };
  selectArr.value[subscript] = proxy.$utils.formatFunction(query, {
    ...selectArr.value[subscript],
  });
  for (let key in obj) {
    selectArr.value[subscript][key] = obj[key];
  }
};

defineExpose({ open });
</script>

<style lang="scss" scoped>
</style>
